<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
    <meta http-equiv="X-UA-Compatible" content="ie=edge,chrome=1">
    <meta name="referrer" content="never">
    <title>WebSocket</title>
    <link rel="stylesheet" href="../lib/layui-v2.5.7/layui/css/layui.css">
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        ul {
            list-style: none;
        }

        p {
            line-height: 30px;
        }
        p.right {
            text-align: right;
        }

        p.center {
            font-size: 13px;
            color: #999;
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="layui-container">
        <button class="layui-btn connect">建立连接</button>
        <button class="layui-btn close">断开连接</button>

        <div class="layui-form-item" style="margin-top: 20px;">
            
            <div class="layui-input-inline">
                <input type="text" class="layui-input ipt" placeholder="请输入内容" autocomplete="off">
            </div>
            <button class="layui-btn send">发送消息</button>
        </div>

        <div class="layui-card">
            <div class="layui-card-body room">
                
            </div>
        </div>
    </div>

    <script src="../lib/layui-v2.5.7/layui/layui.all.js"></script>
    <script type="text/javascript">
        // if("WebSocket" in window){
        //     alert("浏览器支持");
        // }

        // 应用场景： K线图  聊天

        var $ = layui.$,
            ws = null;

        $(".connect").click(function (){
            // ws://  wss://
            ws = new WebSocket("ws://127.0.0.1:9000/robot");

            ws.onopen = function (){
                console.log("连接成功了");
            }

            ws.onmessage = function (e){
                console.log("后台返回的数据：", e.data);
                $(".room").append(`<p class="left">服务器：${ e.data }</p>`);
            }

            ws.onclose = function (){
                console.log("断开连接了");
                $(".room").append(`<p class="center">断开连接了</p>`);
            }
        })


        $(".close").click(function (){
            // 如果ws是连接状态，我们断开
            // readyState 0 未连接   1  连接中   2 关闭中   3 已关闭或有意外
            if(ws && ws.readyState == 1){
                ws.close();
            }
        })

        $(".send").click(function (){
            // 有值校验
            if(ws && ws.readyState == 1){
                ws.send($(".ipt").val());
                $(".room").append(`<p class="right">自己：${ $(".ipt").val() }</p>`);
                $(".ipt").val("");
            }
        })
    </script>
</body>
</html>